/**
 * Copyright 2010 Jake Jackson
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jake.nb.ext.ant.parser;

import java.util.Collection;
import java.util.HashSet;
import javax.swing.text.Document;

/**
 *
 * @author JakeJ
 */
public class Spans {

  final Collection<Span> spans;
  private final Document document;

  Spans(final Document document) {
    spans = new HashSet<Span>();
    this.document = document;
  }

  void addSpan(int[] span) {
    spans.add(new Span(document, span[0], span[1]));
  }

  void addSpan(int start, int end) {
    spans.add(new Span(document, start, end));
  }

  void addSpan(Span span) {
    spans.add(span);
  }

  void addSpans(final Collection<Span> otherSpans) {
    spans.addAll(otherSpans);
  }

  void addSpans(final Spans otherSpans) {
    spans.addAll(otherSpans.getSpans());
  }

  public boolean isInside(final int offset) {
    return getSpan(offset) != null;
  }

  /**
   * Checks the passed span is inside one of the spans contained in here.
   * @param span
   * @return
   */
  public boolean isCompletelyInside(final Span span) {
    boolean ret = false;
    for (final Span usedInHere : spans) {
      if(usedInHere.getStart() <= span.getStart() && usedInHere.getEnd() >= span.getEnd()) {
        ret = true;
        break;
      }
    }
    return ret;
  }

  public Span getSpan(final int offset) {
    Span retSpan = null;
    for (final Span span : spans) {
      if(span.getStart() <= offset && span.getEnd() >= offset) {
        retSpan = span;
        break;
      }
    }
    return retSpan;
  }

  public Collection<Span> getSpans() {
    return new HashSet<Span>(spans);
  }

  @Override
  public String toString() {
    return "Spans{" + "spans=" + spans + "document=" + document + '}';
  }
}
